import { checkArg } from "../utils/check";
import { DBMgr } from "./db";
import { INVALID_PARAMETER } from "./err";

export class ChapterModule {
    static ins: ChapterModule;

    // 添加新的分会机构
    async addChapter(argv: { 
        name: string, 
        country: string,
        province: string,
        city: string 
    }) {
        let checkRes = checkArg(argv, "name")
        if (checkRes) {
            return INVALID_PARAMETER;
        }

        // 检查机构名是否已存在
        const existingChapter = await DBMgr.ins.prisma.t_chapter.findFirst({
            where: { name: argv.name }
        });

        if (existingChapter) {
            return { code: -1, msg: "分会机构名称已存在" };
        }

        // 创建新机构
        const newChapter = await DBMgr.ins.prisma.t_chapter.create({
            data: {
                name: argv.name,
                country: argv.country,
                province: argv.province,
                city: argv.city,
                create_time: new Date(),
                update_time: new Date()
            }
        });

        return { code: 0, data: newChapter };
    }

    // 更新分会机构信息
    async updateChapter(argv: { 
        chapterId: number, 
        name?: string, 
        country?: string,
        province?: string,
        city?: string
    }) {
        let checkRes = checkArg(argv, "chapterId")
        if (checkRes) {
            return INVALID_PARAMETER;
        }

        // 如果要更新名称，先检查新名称是否已存在
        if (argv.name) {
            const existingChapter = await DBMgr.ins.prisma.t_chapter.findFirst({
                where: { 
                    name: argv.name,
                    id: { not: argv.chapterId }
                }
            });

            if (existingChapter) {
                return { code: -1, msg: "分会机构名称已存在" };
            }
        }

        // 更新机构信息
        const updatedChapter = await DBMgr.ins.prisma.t_chapter.update({
            where: { id: argv.chapterId },
            data: {
                name: argv.name,
                country: argv.country,
                province: argv.province,
                city: argv.city,
                update_time: new Date()
            }
        });

        return { code: 0, data: updatedChapter };
    }

    // 查询分会机构列表
    async getChapterList(argv: { 
        keyword?: string,
        country?: string,
        province?: string,
        city?: string,
        page?: number,
        pageSize?: number 
    }) {
        const page = argv?.page || 1;
        const pageSize = argv?.pageSize || 10;
        const skip = (page - 1) * pageSize;

        let where: any = {};
        
        // 构建查询条件
        if (argv?.keyword) {
            where.name = { contains: argv.keyword };
        }
        if (argv?.country) {
            where.country = argv.country;
        }
        if (argv?.province) {
            where.province = argv.province;
        }
        if (argv?.city) {
            where.city = argv.city;
        }

        // 获取总数
        const total = await DBMgr.ins.prisma.t_chapter.count({ where });

        // 获取分页数据
        const chapters = await DBMgr.ins.prisma.t_chapter.findMany({
            where,
            skip,
            take: pageSize,
            orderBy: { create_time: 'desc' }
        });

        return { 
            code: 0, 
            data: {
                list: chapters,
                total,
                page,
                pageSize
            }
        };
    }

        // 删除分会机构
        async deleteChapter(argv: { chapterId: number }) {
            let checkRes = checkArg(argv, "chapterId")
            if (checkRes) {
                return INVALID_PARAMETER;
            }
    
            // 检查是否存在关联用户
            const associatedUsers = await DBMgr.ins.prisma.t_user.count({
                where: { chapter: argv.chapterId.toString() }
            });
    
            if (associatedUsers > 0) {
                return { code: -1, msg: "该机构下还有关联用户，无法删除" };
            }
    
            // 删除机构
            await DBMgr.ins.prisma.t_chapter.delete({
                where: { id: argv.chapterId }
            });
    
            return { code: 0, msg: "删除成功" };
        }

    // 获取单个分会机构详情
    async getChapterDetail(argv: { chapterId: number }) {
        let checkRes = checkArg(argv, "chapterId")
        if (checkRes) {
            return INVALID_PARAMETER;
        }

        const chapter = await DBMgr.ins.prisma.t_chapter.findUnique({
            where: { id: argv.chapterId }
        });

        if (!chapter) {
            return { code: -1, msg: "分会机构不存在" };
        }

        return { code: 0, data: chapter };
    }

    // 在 ChapterModule 类中添加 getChapterMembers 方法
    async getChapterMembers(argv: { chapter: string }) {
        let checkRes = checkArg(argv, "chapter")
        if (checkRes) {
            return INVALID_PARAMETER;
        }

        // 查询与该分会ID相关联的所有成员
        const members = await DBMgr.ins.prisma.$queryRaw`
            SELECT 
                u.*, 
                s.* 
            FROM 
                t_user u 
            LEFT JOIN 
                t_sunchart s ON u.id = s.uid 
            WHERE 
                u.removed = 0 AND 
                s.removed = 0 AND 
                u.chapter = ${argv.chapter.toString()}
        `;

        return { code: 0, data: members };
    }


}

ChapterModule.ins = new ChapterModule(); 